package ntd.util.frame.msg.service.handle.aliyun;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import ntd.util.frame.msg.bo.MsgInBO;
import ntd.util.frame.msg.MsgHandle;
import ntd.util.frame.msg.service.context.MsgContext;
import ntd.util.modular.function.entity.ChannelBusiness;

public class AliyunMsgHandle implements MsgHandle {

    @Override
    public Boolean handle(MsgContext msgContext) {
        if (msgContext.getAction().equals("sendMsg")) {
            return sendMsg(msgContext);
        }
        return Boolean.FALSE;
    }

    private Boolean sendMsg(MsgContext msgContext) {
        MsgInBO msgInBO = msgContext.getMsgInBO();
        ChannelBusiness channelBusiness = msgContext.getChannelBusiness();
        JSONObject settingJson = JSONUtil.parseObj(channelBusiness.getSettingJson());
        IAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(settingJson.getStr("regionId"),
                channelBusiness.getAppKey(), channelBusiness.getAppSecret()));
        CommonRequest request = initCommonRequest();

        JSONObject dataJson = JSONUtil.parseObj(ObjectUtil.defaultIfBlank(msgInBO.getDataJson(), "{}"));

        request.putQueryParameter("RegionId", settingJson.getStr("regionId"));
        request.putQueryParameter("SignName", ObjectUtil.defaultIfBlank(dataJson.getStr("SignName"), settingJson.getStr("SignName")));

        request.putQueryParameter("PhoneNumbers", msgInBO.getReceiverPhones());
        request.putQueryParameter("TemplateCode", dataJson.getStr("templateCode"));
        request.putQueryParameter("TemplateParam", dataJson.getStr("templateParam"));
        try {
            CommonResponse response = client.getCommonResponse(request);
            StaticLog.info("短信发送结果 -----> ：",response.getData());
        } catch (ClientException e) {
            StaticLog.error(e, "[阿里云][短信][{}]失败...");
        }
        return Boolean.TRUE;
    }

    private CommonRequest initCommonRequest() {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        return request;
    }
}
